package net.caidingke.shepherd.controller;

import io.swagger.annotations.ApiOperation;
import net.caidingke.shepherd.controller.base.BasicController;
import net.caidingke.shepherd.domain.user.Role;
import net.caidingke.shepherd.domain.user.User;
import net.caidingke.shepherd.domain.user.request.UserRoleRequest;
import net.caidingke.shepherd.exception.NotFoundException;
import net.caidingke.shepherd.profile.CurrentUser;
import net.caidingke.shepherd.service.UserService;
import net.caidingke.shepherd.utils.constant.GlobalConfig;
import net.caidingke.shepherd.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author bowen.
 */
@RestController
@RequestMapping(value = GlobalConfig.API_PRE_FIX)
public class UserRoleController extends BasicController {

    private final UserService userService;

    @Autowired
    public UserRoleController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "获取角色列表")
    @GetMapping("/roles")
    public Result<List<Role>> roles(@CurrentUser User user) {
        return ok(userService.findRoles(user));
    }

    @ApiOperation(value = "根据ID获取角色")
    @GetMapping("/role/{id}")
    public Result<Role> role(@CurrentUser User user, @PathVariable Long id) {
        return ok(userService.findRoleById(id).orElseThrow(NotFoundException::new));
    }

    @ApiOperation(value = "创建角色")
    @PostMapping("/role")
    public Result role(@RequestBody UserRoleRequest request) {
        userService.saveRole(request);
        return ok();
    }

    @ApiOperation(value = "修改角色权限")
    @PutMapping(value = "/role/{id}")
    public Result modifyRolePermissions(@PathVariable("id") Long roleId, @RequestParam(value = "permissions[]", required = false) List<Long> permissions) {
        userService.modifyRolePermission(roleId, permissions);
        return ok();
    }
}
